package com.shiwaixiangcun.monitor.config;

import com.shiwaixiangcun.core.scheduler.DynamicSchedulerFactory;
import com.shiwaixiangcun.monitor.scheduler.WorkOrderTimeOutJob;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;

/**
 * Created by Administrator on 2017/11/30.
 */
@Configuration
public class SchedulerConfig {

    @Value("${scheduler.auto.startup}")
    private Boolean startup;

    @Bean
    public SchedulerFactoryBean getSchedulerFactoryBean(DataSource dataSource) {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setAutoStartup(startup);
        schedulerFactoryBean.setDataSource(dataSource);
        schedulerFactoryBean.setTriggers(configTriggersList());
        return schedulerFactoryBean;
    }

    @Bean
    public DynamicSchedulerFactory dynamicSchedulerFactory(Scheduler scheduler) {
        DynamicSchedulerFactory dynamicSchedulerFactory = new DynamicSchedulerFactory();
        dynamicSchedulerFactory.setScheduler(scheduler);
        return dynamicSchedulerFactory;
    }


    private Trigger[] configTriggersList() {
        return new Trigger[]{
                workOrderTimeOutJobCronTrigger().getObject()
        };
    }

    @Bean
    public JobDetailFactoryBean workOrderTimeOutJob() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(WorkOrderTimeOutJob.class);
        factoryBean.setDurability(true);
        return factoryBean;
    }

    @Bean
    public CronTriggerFactoryBean workOrderTimeOutJobCronTrigger() {
        JobDetailFactoryBean jobDetailFactoryBean = workOrderTimeOutJob();
        CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
        factoryBean.setJobDetail(jobDetailFactoryBean.getObject());
        String workOrderCron = "0 */1 * * * ?";
        factoryBean.setCronExpression(workOrderCron);
        return factoryBean;
    }


}
